import { defineStore } from 'pinia'
import { parse } from 'acorn'
import { simple, SimpleVisitors } from 'acorn-walk'
import useInteraction from '@/hooks/useInteraction'

export default defineStore('config', {
  state: () => ({
    theme: 'dark' as 'dark' | 'light',
    dicts: {} as Record<string, DictItem[]>
  }),
  getters: {
    isDark: (state) => state.theme === 'dark'
  },
  actions: {
    async setDicts() {
      if (!Object.keys(this.dicts).length) {
        const { content } = (await useInteraction({
          type: 'tool',
          eventName: 'get-dicts'
        })) as { content: string }

        simple(parse(content, { ecmaVersion: 2021, sourceType: 'module' }), {
          VariableDeclarator: ({ id, init }) => {
            this.dicts[id.name] = init.elements.map((v) =>
              v.properties.reduce((dicts, v) => {
                dicts[v.key.name] = v.value.value
                return dicts
              }, {})
            )
          }
        } as SimpleVisitors<'VariableDeclarator'>)
      }
    }
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'config',
        storage: localStorage
      }
    ]
  }
})
